<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Orders extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/orders/', 'Заказы');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{

		$data['from'] = $from = $this->input->get('from', true);
		$status = $this->input->get('status', true);
		if ($from == "") $from = 0;
		$this->db->select("orders.*, meta.first_name")->from('orders')->join('meta', 'meta.user_id = orders.order_user', 'left')->order_by('order_date', 'desc')->where('order_userdata != ', '');
		if ($status !== false) $this->db->where('order_status', $status);
		if ($this->input->server('REQUEST_METHOD') == "POST") {
			if ($this->input->post('text') != "") {
				$s_text = explode(" ",$this->input->post('text'));
				$like = "(";
						if (preg_match("/\d{2}\.\d{2}\.\d{4}/", $this->input->post('text'), $matches)) {
							$start = strtotime($matches[0]);
							$end = strtotime($matches[0]) + 86400;
							$like .= "ci_orders.order_date >= ".$start." and ci_orders.order_date <= ".$end."";
						} else {
							$k = 0;
							foreach ($s_text as $s_seg) {
								$s_seg = trim($s_seg);
								if ($s_seg != "") {
								$k++;
									if ($k != 1) $like .= " or ";
									$like .= "ci_orders.order_id = '".$s_seg."' or ";
									$like .= "ci_orders.order_sum = '".$s_seg."' or ";
									$like .= "ci_orders.order_sum2 = '".$s_seg."' or ";
									$like .= "ci_orders.order_userdata like '%".$s_seg."%'";
								}
							}
				}
				$like .= ")";
				$this->db->where($like);
			}
		} else {
			$this->db->limit($this->perpage, $from);
		}
		$data['pages'] = $pages = $this->db->get()->result_array();
		/* pagination */
		if ($this->input->server('REQUEST_METHOD') != "POST") {
			$this->db->select()->from('orders')->where('order_userdata != ', '');
			if ($status !== false) $this->db->where('order_status', $status);
			$count = $this->db->count_all_results();
			if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
				$pgng = $from - $this->perpage;
				redirect('admin/orders/index/?from='.$pgng);
			}
			$this->load->library('pagination');
			$config['base_url'] = '/admin/orders/index/';
			$config['total_rows'] = $count;
			$config['page_query_string'] = TRUE;
			$config['per_page'] = $this->perpage;
			$this->pagination->initialize($config);
			$data['paging'] = $this->pagination->create_links();
		}
		/* pagination */

		$this->layout->view('admin/orders/index', $data);
	}
	public function edit($id) {
		$this->crumps->push('/admin/orders/'.($id == 0?'add':'edit/'.$id).'/', "Просмотр");
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('orders')->where('order_id', $id)->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/orders');
		$data['user'] = $this->db->select()->from('users')->where('id', $page['order_user'])->get()->row_array();
		$data['meta'] = $this->db->select()->from('meta')->where('user_id', $page['order_user'])->get()->row_array();
		$data['qiwi'] = $this->_result_status($page['order_qstatus']);

		$url = "http://service.qtelecom.ru/public/http/";
		$ch = curl_init();

		$post = "user=".$this->config->item('sms_user');
		$post .= "&pass=".$this->config->item('sms_pass');
		$post .= "&action=balance";
		$post .= "&gzip=none";
		$post .= "&HTTP_ACCEPT_LANGUAGE=ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3";

		curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
		curl_setopt($ch, CURLOPT_POST, 1); // set POST method
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // add POST fields
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type' => 'application/x-www-form-urlencoded'));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		$result = curl_exec($ch); // run the whole process

		$xml = simplexml_load_string($result);

		$balance = $xml->balance->AGT_BALANCE;
		$overdraft = $xml->balance->OVERDRAFT;

		$form = new jQuickForm('simple');

		$smscan = (floatval($balance) + floatval($overdraft)) / $this->config->item('one_sms_price');

		$form->insertStatic("<div style='float: right;'>Баланс лицегого счета ".$balance." руб, овердрафт ".$overdraft." руб. Можно отправить <b>".round($smscan)." сообщений</b></div>");

		$form->insertTextArea('sms')->setLabel('Текст sms сообщения для отправки')->setId('check_length')->setComment('Вы набрали <span class="keypressed_symbols">0</span> символов, одна смс вмещает 160 русских символов.')->addRuleRequired('Обязательное поле');

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate() && $this->input->post('sms') !== FALSE) {
			$p_data = $this->input->post();
			if ($p_data['sms'] != "" && mb_strlen($p_data['sms']) <= 480) {
				$url = "http://service.qtelecom.ru/public/http/";
				$ch = curl_init();

				$post = "user=".$this->config->item('sms_user');
				$post .= "&pass=".$this->config->item('sms_pass');
				$post .= "&action=post_sms";
				$post .= "&message=".$p_data['sms'];
				$post .= "&gzip=none";
				$post .= "&target=".preg_replace("/[^0-9\+]*/", "", $data['meta']['phone']);
				$post .= "&sender=".$this->config->item('sms_from');
				$post .= "&HTTP_ACCEPT_LANGUAGE=ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3";

				curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
				curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
				curl_setopt($ch, CURLOPT_POST, 1); // set POST method
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // add POST fields
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type' => 'application/x-www-form-urlencoded'));
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				$result = curl_exec($ch); // run the whole process
				$this->session->set_flashdata('msg', 'SMS встала в очередь на отправку');
				curl_close($ch);
				redirect('admin/orders/edit/'.$id.'/');
				exit();
			}
		}

		$gr = $form->insertGroupSubmit();
		$gr->insertInputSubmit("Отправить смс на номер ".$data['meta']['phone']);

		$form2 = new jQuickForm('simple2');

		$form2->insertInputText('order_track')->setLabel('Номер трекинга');

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form2->validate() && $this->input->post('order_track') !== FALSE) {
			$p_data = $this->input->post();
			$this->db->set('order_track', $p_data['order_track'])->where('order_id', $id)->update('orders');

			$mdata['order'] = $this->db->select()->from('orders')->where('order_id', $id)->get()->row_array();

					$this->load->library('email');
					$msg = $this->load->view('admin/orders/to_user_about_tracking', $mdata, true);
					$this->email->from($this->config->item('from_email'), $this->config->item('from_name'));
					$this->email->to($mdata['order']['order_email']);
					$this->email->subject('Изменение номера трекинга заказа на сайте ' . $this->config->item('company_name') . '. Заказ №' . $id);
					$this->email->message($msg);
					$this->email->send();
					$this->email->clear();

			$this->session->set_flashdata('msg', 'Номер трекинга обновлен<br />Сообщение отправлено');
			redirect('admin/orders/edit/'.$id.'/');
			exit();
		}

		$gr = $form2->insertGroupSubmit();
		$gr->insertInputSubmit("Сохранить номер трекинга");

		$form2->addDataSource(new HTML_QuickForm2_DataSource_Array($page));

		$data['form'] = $form."";
		$data['form2'] = $form2."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/orders/show', $data);
	}
	public function set($id, $status) {
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('orders')->where('order_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/orders');
		$this->db->where('order_id', $id)->update('orders', array('order_status' => $status));

		$mdata['order'] = $this->db->select()->from('orders')->where('order_id', $id)->get()->row_array();

		$this->load->library('email');
		$msg = $this->load->view('admin/orders/to_user_about_status', $mdata, true);
		$this->email->from($this->config->item('from_email'), $this->config->item('from_name'));
		$this->email->to($mdata['order']['order_email']);
		$this->email->subject('Изменение cтатуса заказа на сайте ' . $this->config->item('company_name') . '. Заказ №' . $id);
		$this->email->message($msg);
		$this->email->send();
		$this->email->clear();

		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/orders/edit/'.$id.'/');
	}
	function _result_status($code) {
		switch ($code) {
			case "50": $html = 'Выставлен'; break;
			case "52": $html = 'Проводится'; break;
			case "60": $html = 'Оплачен'; break;
			case "150": $html = 'Отменен (ошибка на терминале)'; break;
			case "151": $html = 'Отменен (ошибка авторизации: недостаточно средств на балансе, отклонен абонентом при оплате с лицевого счета оператора сотовой связи и т.п.).'; break;
			case "160": $html = 'Отменен'; break;
			case "161": $html = 'Отменен (Истекло время)'; break;
		}
		return $html;
	}
}